#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年3月8日

@author: Administrator
'''
from account import settings
from account.models import Group
from common.decorators import login_required
from django.db.models.query_utils import Q
from django.http.response import HttpResponse
from django.template.response import TemplateResponse
from funcresource.decorators import user_funcresource
import copy
import ujson as json


@login_required
@user_funcresource
def index(request, template="account/admin/group/group.html"):
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    return TemplateResponse(request, template, rsp_data)
    
@login_required
def list(request):
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = []
    start = int(request.POST['start'])
    length = int(request.POST['length'])
    keyword = request.POST["search[value]"]
    draw = request.POST['draw']
    count = Group.objects.filter(Q(name__icontains=keyword)).count()
    groups = Group.objects.filter(Q(name__icontains=keyword))[start:start + length]
    for group in groups:
        record = {
            "id":group.id,
            "name":group.name,
            "parent_name":group.parent.name if group.parent else "",
            "remark":group.remark,
        }
        rsp_data["data"].append(record)
    rsp_data["recordsTotal"] = count
    rsp_data["recordsFiltered"] = count
    rsp_data["draw"] = draw
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
        
